
package com.joysuch.wwyt.dataimport.controller;

import com.google.gson.*;
import com.joysuch.wwyt.bp.bean.facility.BpProductionAddBean;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpProductionFacility;
import com.joysuch.wwyt.bp.entity.BpProductionFacilityType;
import com.joysuch.wwyt.bp.enums.ProductionFacilityStates;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.bp.repository.BpProductionFacilityDao;
import com.joysuch.wwyt.bp.repository.BpProductionFacilityTypeDao;
import com.joysuch.wwyt.bp.service.*;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.MapUtils;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseLoginAccountService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.dataimport.bean.DataimportValidationResult;
import com.joysuch.wwyt.dataimport.bean.MonitorPointBean;
import com.joysuch.wwyt.dataimport.bean.ProductionFacilityBean;
import com.joysuch.wwyt.dataimport.service.DataImportService;
import com.joysuch.wwyt.dataimport.service.DataImportValidator;
import com.joysuch.wwyt.dataimport.util.DataImportUtils;
import com.joysuch.wwyt.mh.BizUtils;
import com.joysuch.wwyt.mh.entity.MhMajorHazard;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.entity.MhMonitoringType;
import com.joysuch.wwyt.mh.repository.*;
import com.joysuch.wwyt.risk.entity.RiskDistrict;
import com.joysuch.wwyt.risk.repository.RiskDistrictDao;
import com.joysuch.wwyt.risk.repository.RiskPointDao;
import com.joysuch.wwyt.risk.service.RiskDistrictEvaluationService;
import com.joysuch.wwyt.risk.service.RiskPointService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/data-import/single")
public class DataImportSingleController {

    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private RiskDistrictDao riskDistrictDao;
    @Autowired
    private RiskDistrictEvaluationService riskDistrictEvaluationService;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private RiskPointService riskPointService;
    @Autowired
    private MhMonitoringTypeDao monitoringTypeDao;
    @Autowired
    private MhMonitoringPointDao monitoringPointDao;
    @Autowired
    private BpProductionFacilityTypeDao bpProductionFacilityTypeDao;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private BpProductionFacilityService bpProductionFacilityService;
    @Autowired
    private MhMajorHazardDao mhMajorHazardDao;
    @Autowired
    private MhMajorHazardChemProductDao mhChemProductDao;
    @Autowired
    private MhMajorHazardChemProductRelDao mhMajorHazardChemProductRelDao;
    @Autowired
    private BpStorageTankAreaService storageTankAreaService;
    @Autowired
    private BpStorageTankService storageTankService;
    @Autowired
    private BpIndustrialPipelineService industrialPipelineService;
    @Autowired
    private BpEmergencyContingencyPlanService bpEmergencyContingencyPlanService;
    @Autowired
    private BaseLoginAccountService baseLoginAccountService;
    @Autowired
    private DataImportService dataimportService;

//    /**
//     * 导入监测点及监测类型
//     *
//     * @param file
//     * @param
//     * @return
//     */
//    @RequestMapping("monitor-point-by-excel")
//    @org.springframework.transaction.annotation.Transactional
//    public Object importMonitoPointAndFacility(MultipartFile file, @RequestParam(defaultValue = "0") int sheet) {
//        List<MonitorPointBean> jobs = parseData(file, sheet, MonitorPointBean.class);
//        //去模板示例
//        jobs.remove(0);
//        int successCount = 0;
//        Map<String, MhMonitoringPoint> pointCodeMap = new HashMap<>();
//        List<DataimportValidationResult> validations = DataImportValidator.batchValidate(jobs);
//        if (validations.size() > 0) {
//            return formatMsg(validations, true);
//        }
//        for (MonitorPointBean rb : jobs) {
//            DataImportUtils.trimData(rb);
//            validate(rb);
//            if (StringUtils.isNotBlank(rb.getCode())) {
//                MhMonitoringPoint point = saveMhMonitoringPoint(rb);
//                pointCodeMap.put(point.getPointCode(), point);
//                successCount++;
//            }
//        }
//        return ResultBean.success("导入成功，共导入" + successCount + "个监测点,");
//    }
//
//    /**
//     * 导入生产装置
//     *
//     * @param file
//     * @param
//     * @return
//     */
//    @RequestMapping("facility-by-excel")
//    @org.springframework.transaction.annotation.Transactional
//    public Object importFacility(MultipartFile file, @RequestParam(defaultValue = "0") int sheet,
//                                 @RequestParam(defaultValue = "true") boolean parseLocationFromDistrict) {
//        List<ProductionFacilityBean> facilities = parseData(file, sheet, ProductionFacilityBean.class);
//        List<DataimportValidationResult> validations = DataImportValidator.batchValidate(facilities);
//        if (validations.size() > 0) {
//            return formatMsg(validations, true);
//        }
//        int facilityCount = 0;
//        for (ProductionFacilityBean p : facilities) {
//            DataImportUtils.trimData(p);
//            saveProductionFacility(p, new HashMap<>(), parseLocationFromDistrict);
//            facilityCount++;
//        }
//
//        return ResultBean.success("导入成功，共导入" + facilityCount + "个装置");
//    }
//
//    private void saveProductionFacility(ProductionFacilityBean p, Map<String, MhMonitoringPoint> pointCodeMap,
//                                        boolean parseLocationFromDistrict) {
//        BpProductionFacilityType type = bpProductionFacilityTypeDao.findByName(p.getType());
//        if (type == null) {
//            type = new BpProductionFacilityType();
//            type.setName(p.getType());
//            type.setNumber(0);
//            bpProductionFacilityTypeDao.save(type);
//        }
//
//        BpProductionFacility facility = bpProductionFacilityDao.findByCode(p.getCode());
//        BpProductionAddBean bean = new BpProductionAddBean();
//        if (facility != null) {
//            bean.setId(facility.getId());
//        }
//        bean.setName(p.getName());
//        bean.setCode(p.getCode());
//        bean.setDepartId(bpDepartDao.findIdByCode(p.getDepartCode()));
//        bean.setEquipmentModel(p.getModelNo());
//        bean.setKeyEquipment("是".equals(p.getKeyEquipment()) ? "Y" : "N");
//        // bean.setFunctions(p.get);
//        bean.setLocation(parseLocationOfDistrict(p.getLocation(), p.getFloor(), parseLocationFromDistrict));
//        System.out.println("p.getMajorHazardCode()=" + p.getMajorHazardCode());
//        System.out.println("p.getLocation()=" + p.getLocation());
//        bean.setMajorHazardId(findMajorHazardIdByCode(p.getMajorHazardCode()));
//        bean.setProductionAbility(p.getProductionAbility());
//        bean.setTechnicalCondition(p.getTechCondition());
//        ProductionFacilityStates state = ProductionFacilityStates.findByName(p.getState());
//        bean.setState(state == null ? null : state.getId());
//        bean.setType(type.getId());
//        bean.setMonitorIdss(extractMonitorPointIds(p, pointCodeMap));
//
//        try {
//            System.out.println(Arrays.toString(bean.getMonitorIdss()));
//            if (facility == null) {
//                bpProductionFacilityService.add(bean);
//            } else {
//                bpProductionFacilityService.update(bean);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private String parseLocationOfDistrict(String location, Integer floor, boolean parseLocationFromDistrict) {
//        if (!parseLocationFromDistrict) {
//            return location;
//        }
//        try {
//            List<RiskDistrict> districts = riskDistrictDao.findByCode(location);
//            if (!CollectionUtils.isEmpty(districts)) {
//                List<Point> points = MapUtils.parsePointsFromJson(districts.get(0).getCoordinates());
//                if (points != null) {
//                    Point point = MapUtils.calculateCenterPoint(points);
//                    Map<String, Object> map = new HashMap<>();
//                    map.put("x", point.getX());
//                    map.put("y", point.getY());
//                    map.put("floorId", (floor == null || floor <= 0) ? 1 : floor);
//                    return new GsonBuilder().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
//                        @Override
//                        public JsonElement serialize(final Double src, final Type typeOfSrc,
//                                                     final JsonSerializationContext context) {
//                            BigDecimal value = BigDecimal.valueOf(src);
//                            return new JsonPrimitive(value);
//                        }
//                    }).create().toJson(map);
//                }
//            }
//        } catch (Exception e) {
//        }
//        return location;
//    }
//
//    private ResultBean formatMsg(List<DataimportValidationResult> validations, boolean html) {
//        StringBuilder sb = new StringBuilder();
//        for (DataimportValidationResult r : validations) {
//            sb.append("第").append(r.getRowIndex()).append("行: ");
//            sb.append(StringUtils.join(r.getErrors().values(), ","));
//            sb.append(html ? "<br>" : "\n");
//        }
//        return ResultBean.fail(402, sb.toString());
//    }
//
//    private Long findMajorHazardIdByCode(String majorHazardCode) {
//        MhMajorHazard mh = mhMajorHazardDao.findByCode(majorHazardCode);
//        System.out.println("mh.getId()=" + mh);
//        return mh == null ? null : mh.getId();
//    }
//
//    private Long findDepardIdByName(String departName) {
//        BpDepart depart = bpDepartDao.findFirstByName(departName);
//        return depart == null ? null : depart.getId();
//    }
//
//    private void validate(MonitorPointBean rb) {
//
//    }
//
//    // 保存监测点
//    private MhMonitoringPoint saveMhMonitoringPoint(MonitorPointBean rb) {
//        String mType = rb.getType();
//        String sType = mType.substring(0, mType.indexOf("(")).trim();
//        String eType = mType.substring(mType.indexOf("("), mType.indexOf(")")).trim();
//        MhMonitoringType type = monitoringTypeDao.findFirstByName(sType);
//        if (type == null) {
//            //新类型不做新增
//            throw new IllegalArgumentException(rb.getType() + " 此类型不存在");
////            type = new MhMonitoringType();
////            type.setName(rb.getType());
////            type.setUnit(rb.getUnit());
////            monitoringTypeDao.save(type);
//        }
//        //编号判重
//        Long count = monitoringPointDao.countOfCode(rb.getCode());
//        if (count > 0) {
//            throw new IllegalArgumentException(rb.getCode() + " 此编号已存在");
//        }
//        MhMonitoringPoint point = monitoringPointDao.findByPointCode(rb.getCode());
//        if (point == null) {
//            point = new MhMonitoringPoint();
//            point.setPointCode(rb.getCode());
//        }
//        point.setName(rb.getName());
//
//        point.setMhMonitoringType(type);
//        if (null != eType) {
//            point.setUnit(eType);
//        }
//
//        point.setLowValue1(rb.getLevel1a());
//        point.setLowValue2(rb.getLevel1b());
//
//        point.setHighValue1(rb.getLevel2a());
//        point.setHighValue2(rb.getLevel2b());
//
//        if ("浓度".equals(rb.getType())) {
//            point.setLevel1Threshold(rb.getLevel2a());
//            point.setLevel2Threshold(rb.getLevel2b());
//        } else {
//            point.setLevel1Threshold(point.getLowValue1());
//            point.setLevel2Threshold(point.getHighValue2());
//        }
//        monitoringPointDao.save(point);
//        return point;
//    }
//
//    private Double parseDouble(String level1a) {
//        if (StringUtils.isBlank(level1a)) {
//            return null;
//        }
//        return Double.parseDouble(level1a);
//    }
//
//    private Long[] extractMonitorPointIds(ProductionFacilityBean p, Map<String, MhMonitoringPoint> pointCodeMap) {
//        String codes = p.getMinitorPointCodes();
//        if (StringUtils.isNotBlank(codes)) {
//            List<Long> list = new ArrayList<>();
//            String[] ss = codes.split("\n");
//            for (String s : ss) {
//                s = s.trim();
//                if (s.length() > 0) {
//                    MhMonitoringPoint point = pointCodeMap.get(s);
//                    if (point == null) {
//                        point = monitoringPointDao.findByPointCode(s);
//                    }
//                    Assert.notNull(point, "第" + p.getRowIndex() + "行,监测点编号" + s + "对应的监测点不存在，请检查数据后再导入.");
//                    list.add(point.getId());
//                }
//            }
//            return list.toArray(new Long[0]);
//        }
//        return new Long[0];
//    }
//
//    private <T> List<T> parseData(MultipartFile file, int sheetIndex, Class<T> clazz) {
//        return parseData(file, sheetIndex, clazz, false);
//    }
//
//    private <T> List<T> parseData(MultipartFile file, int sheetIndex, int startRow, Class<T> clazz,
//                                  boolean trimStringData) {
//        try {
//            return DataImportUtils.parseData(file.getInputStream(), sheetIndex, startRow, clazz, trimStringData);
//        } catch (Exception e) {
//            log.error("parse data exception:", e);
//        }
//        return null;
//    }
//
//    private <T> List<T> parseData(MultipartFile file, int sheetIndex, Class<T> clazz, boolean trimStringData) {
//        return parseData(file, sheetIndex, 1, clazz, trimStringData);
//    }
//
//    // 将has开头的文本属性转换为英文字符
//    private void translateHasChineseToYesNo(Object tank) throws Exception {
//
//        PropertyDescriptor[] ps = BeanUtils.getPropertyDescriptors(tank.getClass());
//        for (PropertyDescriptor pd : ps) {
//            if ((pd.getName().startsWith("has") || pd.getName().startsWith("is"))
//                    && pd.getPropertyType() == String.class) {
//                String value = BizUtils.translateChineseToYesNo((String) pd.getReadMethod().invoke(tank, null));
//                pd.getWriteMethod().invoke(tank, value);
//            }
//        }
//    }
//
//    private String floatToString(Float workPressureHighValue) {
//        return workPressureHighValue == null ? "" : workPressureHighValue + "";
//    }
}
